﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Web;
using NPOI.HSSF.Record.Formula.Functions;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace QzgfFrame.Utility.Core.Export
{
    class ExportToPoiExcel:ExportFacade
    {

        public bool Export(out StreamWriter outdata, DataTable list, string sheetName, string[] fields, string[] colName)
        {
            throw new NotImplementedException();
        }

        public bool Export(out byte[] outdata, DataTable list, string sheetName, string[] fields, string[] colName)
        {
            outdata = new byte[] {};
            if (list == null)
            {
                return false;
            }
            try
            {
                //创建工作簿
                var wb = new HSSFWorkbook(); //创建excel文件
                var sheettemp = wb.CreateSheet();
                wb.SetSheetName(0, (String)sheetName);//新建一个sheet

                //=========================行头信息====================
                int j = 0; //占用第一行，这个是根据是否有行头确定的，没有设置为0,有设置为1；
                var rowfield = sheettemp.CreateRow(j); //新增一行用于存放列头内容
                HSSFRichTextString val;
                for (int i = 0; i < colName.Length; i++) //根据获取到的列头数据，循环设置列头的内容
                {
                    var cellfield = rowfield.CreateCell(i); 
                    val = new HSSFRichTextString(colName[i]);
                    cellfield.SetCellValue(val);
                    int xx = cellfield.RichStringCellValue.Length;
                    sheettemp.SetColumnWidth((int) i, (int) 2048*xx); //设置列的宽度,是表头字符串个数的2048倍
                }

                //=========================表体信息======================
                int count = 0;
                //foreach (var curval in list)
                //{
                //    PropertyInfo[] properties = typeof(T).GetProperties(); 
                //    var rowbody = sheettemp.CreateRow(count + j + 1);
                //    for (int i = 0; i < fields.Length; i++)
                //    {
                //        var cellbody = rowbody.CreateCell(i);
                //        var pi = properties.First<PropertyInfo>(x => x.Name == fields[i]);
                //        //全部当字符串处理(ExportUtil中有处理非string类型的例子)
                //        var tvalue = pi.GetValue(curval, null);
                //        val = new HSSFRichTextString(tvalue.ToString());
                //        cellbody.SetCellValue(val);
                //    }
                //    count++; 
                //}


                foreach (DataRow row in list.Rows)
                {
                    IRow dataRow = sheettemp.CreateRow(count + j + 1);
                    for (int i = 0; i < fields.Length; i++)
                    {
                        var cellbody = dataRow.CreateCell(i);
                        //全部当字符串处理(ExportUtil中有处理非string类型的例子)
                        var tvalue = row[fields[i].ToString()].ToString();
                        val = new HSSFRichTextString(tvalue.ToString());
                        cellbody.SetCellValue(val);
                    }
                    count++; 
                }
                //=======================页尾========================

                //=======================将工作薄信息输出==================
                using (var ms = new MemoryStream())
                {
                    wb.Write(ms);
                    ms.Flush();
                    ms.Position = 0;
                    outdata = ms.ToArray();
                }
            }
            catch (IOException e)
            {
                outdata = new byte[] {};
                return false;
            }
            return true;
        }


        //private byte[] DownLoadHelper(XlsDocument xls, Worksheet sheet, string xlsName)
        //{
        //    using (MemoryStream ms = new MemoryStream())
        //    {
        //        xls.Save(ms);
        //        ms.Flush();
        //        ms.Position = 0;
        //        sheet = null;
        //        xls = null;
        //        HttpResponse response = System.Web.HttpContext.Current.Response;
        //        response.Clear();
        //        response.Charset = "UTF-8";
        //        response.ContentType = "application/vnd.ms-excel";
        //        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
        //                                                          string.Format("attachment; filename=" +
        //                                                                        HttpUtility.UrlEncode(xlsName)));
        //        byte[] data = ms.ToArray();
        //        return data;
        //    }
        //}

        //设置样式与风格
        private void SetFieldStyle(HSSFWorkbook wb, HSSFCell row)
        {
            var cellStyle = wb.CreateCellStyle();
            cellStyle.Alignment = HorizontalAlignment.CENTER;
            cellStyle.VerticalAlignment = VerticalAlignment.TOP;

            var font = wb.CreateFont();
            font.FontHeightInPoints = ((short) 11);
            font.FontName = "宋体";
            font.Boldweight = (short)FontBoldWeight.BOLD;
            cellStyle.SetFont(font);
            row.CellStyle = cellStyle;
        }

    }
}
